/**
 * 字段转换
 * fieldMap: {label: 'text'} 新增一个label属性
 * childrenField: 子节点属性
 * @author xiufu.wang
 */
import { objectProperty, isArray, isObject } from 'mars-pro/src/pro/util';
function resolveFieldMapFromData(data, { fieldMap, childrenField }, dataSource) {
    if (data && Object.keys(fieldMap).length > 0) {
        if (isArray(data)) {
            data.forEach(function (r, i) {
                data[i] = resolveFieldMapFromData(r, { fieldMap, childrenField })
            })
        } else {
            if (!isObject(data)) { 
                return data
            }
            //转换对象数据
            Object.keys(fieldMap).forEach(function (k) {
                if (!(k in data) &&  k !== fieldMap[k]) {
                    Object.defineProperty(data, k, {
                        enumerable: true,
                        get() {
                            return typeof fieldMap[k] === 'function' ? fieldMap[k](data) : data[fieldMap[k]]
                        }
                    })
                }
            })
            // 如果是tree data
            if (childrenField && data[childrenField] && Array.isArray(data[childrenField]) && data[childrenField].length > 0) {
                resolveFieldMapFromData(data[childrenField], { fieldMap, childrenField })
            }
        }
    }
    return data
}

export default function (datas, opt, dataSource) {
    if (opt.fieldMap) {
        return resolveFieldMapFromData(datas, opt, dataSource)
    }
    return datas
}